package com.moon.robot.listener;

import com.alibaba.fastjson.*;
import com.forte.common.annotation.Comment;
import com.forte.qqrobot.anno.Filter;
import com.forte.qqrobot.anno.Listen;
import com.forte.qqrobot.anno.ListenBreak;
import com.forte.qqrobot.anno.depend.Beans;
import com.forte.qqrobot.anno.depend.Depend;
import com.forte.qqrobot.anno.template.OnGroup;
import com.forte.qqrobot.beans.cqcode.CQCode;
import com.forte.qqrobot.beans.messages.msgget.GroupAddRequest;
import com.forte.qqrobot.beans.messages.msgget.GroupMsg;
import com.forte.qqrobot.beans.messages.result.GroupMemberList;
import com.forte.qqrobot.beans.messages.types.MsgGetTypes;
import com.forte.qqrobot.beans.types.KeywordMatchType;
import com.forte.qqrobot.sender.MsgSender;
import com.forte.qqrobot.utils.CQCodeUtil;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;




import com.forte.qqrobot.anno.Filter;
import com.forte.qqrobot.anno.Listen;

import com.forte.qqrobot.beans.messages.msgget.GroupAddRequest;
import com.forte.qqrobot.beans.messages.msgget.GroupMsg;
import com.forte.qqrobot.beans.messages.result.GroupMemberList;
import com.forte.qqrobot.beans.messages.types.MsgGetTypes;

import com.forte.qqrobot.sender.MsgSender;
import com.moon.robot.RobotApplication;
import com.moon.robot.Utils.Badiushibie;
import com.moon.robot.Utils.FileUtil;
import com.moon.robot.Utils.Utils;
import com.moon.robot.pojo.*;
import com.moon.robot.service.GroupService;
import com.moon.robot.service.QQService;
import com.moon.robot.service.WebSocket;
import com.simplerobot.modules.delay.DelayHelper;



import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baidu.translate.demo.TransApi;




import com.forte.qqrobot.anno.ListenBreak;
import com.forte.qqrobot.beans.cqcode.CQCode;

import com.forte.qqrobot.beans.types.KeywordMatchType;
import com.forte.qqrobot.utils.CQCodeUtil;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Controller;

import java.io.*;
import java.net.HttpURLConnection;

import java.net.URL;
import java.net.URLEncoder;
import java.util.*;
import java.util.concurrent.TimeUnit;

/**
 * <p> 用作示例的监听器类
 *
 * <p> 类上需要标注@beans，因为此框架存在依赖注入功能。
 *
 * <p> 此示例类中监听函数是与私聊有关的。
 *
 * <p> 当你出现了：发送消息成功无报错、酷Q日志中也显示发送成功无报错，但是实际上机器人没有发出任何消息的时候，此时大概率是消息被屏蔽。
 * 这种情况的原因很多，例如机器人账号异地登录、等级太低、没有活跃度、很少登录、腾讯看你像是机器人等各种因素。
 *
 * <p> 解决办法目前已知可尝试：手动登录bot账号去水群、发消息提升活跃度、多挂机两天摆脱嫌疑、提升活跃度、充值会员（不一定能行）等方法。
 *
 * @author Heilant Gong
 * https://github.com/HeilantG
 */
@Beans
@Comment
public class GroupDemoListener {
    @Autowired
    private GroupService groupService;
    @Autowired
    private QQService qqService;


    private Map<String, String> checklist = new HashMap<String, String>() {{
        put("中文", "zh");
        put("英语", "en");
        put("粤语", "yue");
        put("日语", "jp");
        put("韩语", "kor");
        put("德语", "de");
        put("默认", "auto");
    }};


    private Map<String, String> OCRCheck = new HashMap<String, String>() {{
        put("中文", "CHN_ENG");
        put("英语", "ENG");
        put("日语", "JAP");
        put("韩语", "KOR");
        put("德语", "GER");
        put("默认", "CHN_ENG");
    }};


    private List<Song> songList=new ArrayList<>();
    public static List<String> grouplist = new ArrayList<>();


    /**
     * <p> 测试此监听消息的方法：在机器人所在群发送任意消息。
     *
     * <p> 监听群消息，打印在控制台，不做任何回复。
     *
     * <p> {@link OnGroup}注解代表监听群消息，
     * 他等同于参数为{@link MsgGetTypes#groupMsg}的{@link Listen}
     *
     * <p> 监听注解相关的详细内容参考文档或入群询问：
     * <p> http://simple-robot-doc.forte.love/1408365
     * <p> http://simple-robot-doc.forte.love/1780853
     *
     * <p> 也就是说，@OnGroup 等同于 @Listen(MsgGetTypes.groupMsg)
     * <p> @OnGroup注解属于一种模板注解，其他类似的模板注解参考包路径{@link com.forte.qqrobot.anno.template}下的全部注解。
     *
     * @param groupMsg 由于你监听的是“群消息”，因此你的参数中可以填入私信消息对应的封装接口，即{@link GroupMsg} <br>
     *                 至于其他监听类型应该填写什么参数，你可以参考{@link MsgGetTypes}枚举的元素和他们的参数。基本上都是见明知意的东西。
     */
 /*   @OnGroup
    public void onGroupMsg(GroupMsgs groupMsg) {
        // thisCode 代表当前接收到消息的机器人账号。
        final String botCode = groupMsg.getThisCode();
        // 发消息人的群昵称或者昵称
        final String nickname = groupMsg.getRemarkOrNickname();
        // 发消息人的账号
        final String code = groupMsg.getCode();
        // 接收到消息的群号
        final String groupCode = groupMsg.getGroupCode();
        // 发消息人发的消息
        final String msg = groupMsg.getMsg();

        // 由于拼接的东西比较长，用java自带的MessageFormat对消息进行格式化，会比较直观
        final MessageFormat message = new MessageFormat("机器人{0}接收到了群{1}中{2}({3})发送的群消息：{4}");

        final String printMsg = message.format(new Object[]{botCode, groupCode, nickname, code, msg});

        // 红色显眼儿一点
        System.err.println(printMsg);
    }*/

    /**
     * <p> 测试此监听消息的方法：在机器人所在at他并说：hi
     *
     * <p> 第二个示例，依旧是监听群聊消息，但是多了一个注解：{@link Filter}
     *
     * <p> filter用来过滤接收到的消息的内容，其参数很多，且支持自定义过滤器，详细的相关内容请查阅文档或入群询问 :
     * <p> http://simple-robot-doc.forte.love/1408366
     * <p> http://simple-robot-doc.forte.love/1780854
     * <p> http://simple-robot-doc.forte.love/1536507
     *
     * <p> 此处介绍的主要是filter的at功能与keywordMatchType参数与其中的坑。
     * <p> {@link Filter#at()}参数代表是否只有被at的时候才会触发此监听。听上去很简单，不是吗？
     * 但是首先你要知道，at在qq中也属于消息中的一部分，以Mirai为例，Mirai会将at消息转化为对应的Mirai码，
     * 因此当有人at机器人，并说了一句“hi”的时候，它实际接收到的消息是：“[mirai:at:123456789,@qq昵称] hi”而不是 “hi”或者 “@qq昵称 hi”。
     * 这个时候，假如你不修改{@link Filter#keywordMatchType()}参数的话，你直接匹配“hi”是无法匹配到内容的。
     *
     * <p> keywordMatchType参数内容是枚举{@link KeywordMatchType}，它代表了filter使用什么方式对消息进行匹配，例如正则、equals、contains等。
     * 此示例中，我的参数为{@link KeywordMatchType#RE_CQCODE_TRIM_EQUALS}，它代表：移除消息中的CQ码，并将消息执行trim(), 然后使用equals进行匹配。
     * 因此，at消息中的CQ码移除再trim后，留下的就是你想要匹配的“hi”了。
     *
     * <p> 至于枚举{@link KeywordMatchType}中都有哪些匹配方式，你可以参考文档或者直接点进去看看。基本上枚举名的含义很好猜的，我也全部写了注释。
     *
     * <p> 简单来说@{@link Filter#value()}代表的消息匹配的内容，例如你要监听hi的话就如同下面这个demo所示
     * 如果{@link Filter#keywordMatchType()}不能蛮族你的需求，同时需求并不复杂，可以考虑使用正则表达式来进行监听
     * 例如 @Filter(value = ".*hi.*")就是用来监听所说的话中包含hi的对话
     *
     *
     * @param sender   送信器。所有的监听函数都可以注入这个类，它包含了三大送信器来支持你发送、获取消息。当然，此方法中没有
     *                 sender.SENDER.sendGroupMsg(groupMsg, sendMsg) 之中 groupMsg其实是指群号，sendMsg是需要发送的消息，所以也可以写成
     *                 sender.SENDER.sendGroupMsg(“qq群号”, “消息内容”)
     */

    /*
     * <p> 说明
     * 如果你已经成功配置了Mirai并且运行了demo 那么恭喜您已经成功的搭建了属于你的Mirai机器人
     * 同时，你可能会发现一个奇怪的现象 当你发送 @bot hi 之后 控制台同时输出了第一个方法与第二个方法的输出
     * 这是因为第一个方法并没有配置任何的value进行匹配 所以你的这条消息会同时触发两个监听器，这点需要格外注意
     * */
    @Listen(value = MsgGetTypes.groupAddRequest, sort = 1)
    @ListenBreak
    @Filter()
    public void addgroup(GroupAddRequest groupAddRequest, MsgSender sender) {
        /*sender.SETTER.setGroupAddRequest()*/

        if ("812876658".equals(groupAddRequest.getGroup())){
            if (grouplist==null||grouplist.size()<2){
                GroupMemberList groupMemberList = sender.GETTER.getGroupMemberList("813920989");
                groupMemberList.forEach(qq->{
                    grouplist.add(qq.getQQ());
                });
            }
            for (String a:grouplist){
                if (a.equals(groupAddRequest.getQQ())){
                    sender.SETTER.setGroupAddRequest(groupAddRequest.getFlag(),groupAddRequest.getRequestType(),true," ");
                    return;
                }
            }
            sender.SETTER.setGroupAddRequest(groupAddRequest.getFlag(),groupAddRequest.getRequestType(),false,"不符合条件");

        }

        System.out.println(1);

    }

    @Listen(value = MsgGetTypes.groupMsg, sort = 10)
    @Filter()
    public void groupMsg(GroupMsg groupMsg) {

        GroupMsgs groupMsgs = new GroupMsgs(groupMsg.getGroupCode(), groupMsg.getQQCode(), groupMsg.getPowerType().TO_STRING, groupMsg.getId(), groupMsg.getMsg(), groupMsg.getNickname(), groupMsg.getQQHeadUrl(), groupMsg.getRemark());
        RobotApplication.lastnews.offerFirst(groupMsgs);
        if (RobotApplication.lastnews.size()>10){
            RobotApplication.lastnews.pollLast();
        }

        String groupMsgJson = Utils.GroupMsgToJson(groupMsg);
        /* groupMsg.getNickname()+"("+groupMsg.getQQ()+")"+":"+groupMsg.getMsg()*/

        WebSocket.GroupSending(groupMsgJson);



        for (String a : RobotApplication.allGroup) {
            if (groupMsg.getGroup().equals(a)) {
                RobotApplication.groupcode = true;
                break;
            } else {
                RobotApplication.groupcode = false;
            }
        }

    }

    @Listen(value = MsgGetTypes.groupMsg, sort = 15)
    @Filter(value = "^\\..*", keywordMatchType = KeywordMatchType.TRIM_REGEX)
    public void conterMsg(GroupMsg groupMsg) {
        for (Qq s : RobotApplication.qqList) {
            if (s.getQq().equals(groupMsg.getQQ())) {
                RobotApplication.Jurisdiction = true;
                break;
            } else {
                RobotApplication.Jurisdiction = false;
            }
        }
    }

    @Listen(value = MsgGetTypes.groupMsg, sort = 20)
    @ListenBreak
    @Filter(value = "\\.开启鉴黄", keywordMatchType = KeywordMatchType.TRIM_REGEX)
    public void openMsg(GroupMsg groupMsg, MsgSender sender) {
        if (!RobotApplication.Jurisdiction) {
            return;
        }
        Integer i = groupService.openRobot(groupMsg.getGroup());
        if (i > 0) {
            RobotApplication.allGroup.add(groupMsg.getGroup());
            sender.SENDER.sendGroupMsg(groupMsg.getGroup(), "机器人已开启");
        }
    }

    @Listen(value = MsgGetTypes.groupMsg, sort = 25)
    @ListenBreak
    @Filter(value = "\\.关闭鉴黄", keywordMatchType = KeywordMatchType.TRIM_REGEX)
    public void closeMsg(GroupMsg groupMsg, MsgSender sender) {
        if (!RobotApplication.Jurisdiction) {
            return;
        }
        for (String a : RobotApplication.allGroup) {
            if (a.equals(groupMsg.getGroup())) {
                Integer i = groupService.closeRobot(groupMsg.getGroup());
                if (i > 0) {
                    RobotApplication.allGroup.remove(a);
                    sender.SENDER.sendGroupMsg(groupMsg.getGroup(), "机器人已关闭");
                    return;
                }

            }
        }
        sender.SENDER.sendGroupMsg(groupMsg.getGroup(), "机器人未开启");
    }

    @Listen(value = MsgGetTypes.groupMsg, sort = 30)
    @ListenBreak
    @Filter(value = "^\\..*问.*\\.回答.*", keywordMatchType = KeywordMatchType.TRIM_REGEX)
    public void addMsg(GroupMsg groupMsg, MsgSender sender) throws InterruptedException {
        if (!RobotApplication.groupcode) {
            return;
        }
        if (!RobotApplication.Jurisdiction) {
            return;
        }


        List<String> list = Utils.getMatcher(groupMsg.getMsg(), "^\\.(.*)问(.*)\\.回答(.*)");
        if (list.size() < 3) {
            sender.SENDER.sendGroupMsg(groupMsg.getGroup(), "错误");
            return;
        }
        Reply reply = new Reply(list.get(2).trim(), list.get(3).trim(), groupMsg.getQQ(), list.get(1).equals("模糊") ? 1 : 0);
        int i = groupService.insertMsg(reply);
        if (list.get(1).equals("模糊")) {
            RobotApplication.VagueReplyList.add(new Reply(reply.getId(), reply.getMsg()));
        }
        sender.SENDER.sendGroupMsg(groupMsg.getGroup(), "学会了新的东西，智力upup\n\n新添加的问答id为" + reply.getId());
    }

    @Listen(value = MsgGetTypes.groupMsg, sort = 60)
    @ListenBreak
    @Filter(value = "^\\.查询问答.*", keywordMatchType = KeywordMatchType.TRIM_REGEX)
    public void selMsg(GroupMsg groupMsg, MsgSender sender) throws InterruptedException {
        if (!RobotApplication.groupcode) {
            return;
        }
        if (!RobotApplication.Jurisdiction) {
            return;
        }

        List<String> list = Utils.getMatcher(groupMsg.getMsg(), "^\\.查询问答(.*)");
        if (list.size() < 2) {
            sender.SENDER.sendGroupMsg(groupMsg.getGroup(), "错误");
            return;
        }
        List<Reply> msglist = groupService.selMsgByKey(list.get(1).trim());


        if (msglist != null && msglist.size() > 0) {
            String a = "";
            for (Reply i : msglist) {
                a = a + "id：" + i.getId() + " " + "提问:" + i.getMsg() + " " + "回答:" + i.getAnswer() + " " + "添加者iC:" + i.getAddqq() + "\n";
            }
            sender.SENDER.sendGroupMsg(groupMsg.getGroup(), a);
        }
    }

    @Listen(value = MsgGetTypes.groupMsg, sort = 35)
    @ListenBreak
    @Filter(value = "^\\.删除问答 \\d*", keywordMatchType = KeywordMatchType.TRIM_REGEX)
    public void delMsg(GroupMsg groupMsg, MsgSender sender) throws InterruptedException {
        if (!RobotApplication.groupcode) {
            return;
        }
        if (!RobotApplication.Jurisdiction) {
            return;
        }
        List<String> list = Utils.getMatcher(groupMsg.getMsg(), "^\\.删除问答 (\\d*)");
        if (list.size() < 2) {
            sender.SENDER.sendGroupMsg(groupMsg.getGroup(), "错误");
            return;
        }
        Integer i = groupService.delMsgByID(Integer.parseInt(list.get(1).trim()));
        if (i > 0) {
            sender.SENDER.sendGroupMsg(groupMsg.getGroup(), "感觉忘掉了什么东西\n\n已删除id为" + list.get(1) + "的问答");
        }
    }

    @Listen(value = MsgGetTypes.groupMsg, sort = 40)
    @ListenBreak
    @Filter(value = "^\\.翻译.*", keywordMatchType = KeywordMatchType.TRIM_REGEX)
    public void translateMsg(GroupMsg groupMsg, MsgSender sender) throws InterruptedException {
        if (!RobotApplication.groupcode) {
            return;
        }
        if (!RobotApplication.Jurisdiction) {
            return;
        }
        TransApi api = new TransApi("20191025000344485", "uBF3m9tMTo0Hq8YWvDh1");
        List<String> list = Utils.getMatcher(groupMsg.getMsg(), "^\\.翻译.*\\.(.*) (.*)|^\\.翻译(.*)");
        if (list == null) {
            return;
        }
        if (list.size() == 2) {
            list.add("auto");
        } else {
            try {
                list.set(1, checklist.get(list.get(1)));
            } catch (Exception e) {
                sender.SENDER.sendGroupMsg(groupMsg.getGroup(), "出错了呢");
                return;
            }

        }
        String str = api.getTransResult(list.get(2).trim(), "auto", list.get(1).trim());//中文翻译英文
        JsonObject jsonObj = (JsonObject) new JsonParser().parse(str);//解析json字段
        String res = jsonObj.get("trans_result").toString();//获取json字段中的 result字段，因为result字段本身即是一个json数组字段，所以要进一步解析
        JsonArray js = new JsonParser().parse(res).getAsJsonArray();//解析json数组字段
        jsonObj = (JsonObject) js.get(0);//result数组中只有一个元素，所以直接取第一个元素
        sender.SENDER.sendGroupMsg(groupMsg.getGroup(), list.get(1).trim() + "\n的翻译为：\n" + jsonObj.get("dst").getAsString());
        Thread.currentThread().sleep(1000);
    }
    @Listen(value = MsgGetTypes.groupMsg, sort = 44)
    @Filter(value = "^\\.点歌序列.*", keywordMatchType = KeywordMatchType.TRIM_REGEX)
    @ListenBreak
    public void ChooseSong(GroupMsg groupMsg, MsgSender sender) {
        if (!RobotApplication.Jurisdiction) {
            return;
        }
        if (songList==null||songList.size()<1){
            sender.SENDER.sendGroupMsg(groupMsg.getGroup(), "请搜索歌曲");
            return;
        }
        List<String> list = Utils.getMatcher(groupMsg.getMsg(), "^\\.点歌序列.*第(\\d*)首");
        if (list==null){
            sender.SENDER.sendGroupMsg(groupMsg.getGroup(), "格式错误");
            return;
        }
        String id = songList.get(Integer.parseInt(list.get(1)) - 1).getId();
        sender.SENDER.sendGroupMsg(groupMsg.getGroup(), "[CQ:music,type=163,id=" + id + "]");
    }


    @Listen(value = MsgGetTypes.groupMsg, sort = 45)
    @Filter(value = "^\\.点歌.*", keywordMatchType = KeywordMatchType.TRIM_REGEX)
    public void songMsg(GroupMsg groupMsg, MsgSender sender) throws InterruptedException {
        if (!RobotApplication.Jurisdiction) {
            return;
        }
        List<String> list = Utils.getMatcher(groupMsg.getMsg(), "^\\.点歌(.*)");
        String jsonStr = "";
        if (list.size() > 2) {
            list.set(1, list.get(1) + list.get(2));
        }
        JSONObject jsonObject = null;
        StringBuffer buffer = new StringBuffer();
        try {
            String requestUrl = "http://music.163.com/api/search/pc?s=" + URLEncoder.encode(list.get(1), "utf-8").replaceAll("\\+", "") + "&type=1";

            URL url = new URL(requestUrl);

            HttpURLConnection httpUrlConn = (HttpURLConnection) url.openConnection();

            httpUrlConn.setDoOutput(true);
            httpUrlConn.setDoInput(true);
            httpUrlConn.setUseCaches(false);
// 设置请求方式（GET/POST）
            httpUrlConn.setRequestMethod("GET");
            httpUrlConn.connect();
// 将返回的输入流转换成字符串
            InputStream inputStream = httpUrlConn.getInputStream();
            InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8");
            BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
            String str = null;
            while ((str = bufferedReader.readLine()) != null) {
                buffer.append(str);
            }
            bufferedReader.close();
            inputStreamReader.close();
// 释放资源
            inputStream.close();
            inputStream = null;
            httpUrlConn.disconnect();
            jsonObject = JSONObject.parseObject(buffer.toString());
        } catch (Exception e) {
            e.printStackTrace();
        }

        /*   System.out.println(jsonObject);*/


        JSONArray songs = jsonObject.getJSONObject("result").getJSONArray("songs");
        if (songList!=null||songList.size()>=1){
            songList.clear();
        }

        String msg = "";
        for (int i = 0; i < songs.size(); i++) {
            JSONArray artists = songs.getJSONObject(i).getJSONArray("artists");
            String name = "";
            for (int ii = 0; ii < artists.size(); ii++) {
                if (ii==0){
                    name =name+artists.getJSONObject(ii).getString("name");
                }else {
                    name =name+"/"+ artists.getJSONObject(ii).getString("name");
                }

            }
            Song song = new Song();
            song.setId(songs.getJSONObject(i).get("id").toString());
            song.setSong(songs.getJSONObject(i).get("name").toString());
            song.setArtists(name);
            song.setOrder(i+1);
            songList.add(song);
            msg = msg + song.toString();
        }

        sender.SENDER.sendGroupMsg(groupMsg.getGroup(), msg);


        /* sender.SENDER.sendGroupMsg(groupMsg.getGroup(), "[CQ:music,type=163,id=" + 1 + "]");*/

    }

    @Listen(value = MsgGetTypes.groupMsg, sort = 50)
    @ListenBreak
    @Filter(value = "^\\.添加管理员 \\d*", keywordMatchType = KeywordMatchType.TRIM_REGEX)
    public void addAdmin(GroupMsg groupMsg, MsgSender sender) throws InterruptedException {
        if (!RobotApplication.groupcode) {
            return;
        }
        if (!RobotApplication.Jurisdiction) {
            return;
        }
        List<String> list = Utils.getMatcher(groupMsg.getMsg(), "^\\.添加管理员 (\\d*)");
        if (list.size() < 2) {
            sender.SENDER.sendGroupMsg(groupMsg.getGroup(), "错误");
            return;
        }
        Integer i = qqService.addAdmin(list.get(1));
        if (i > 0) {
            RobotApplication.qqList.add(new Qq(list.get(1).trim()));
            sender.SENDER.sendGroupMsg(groupMsg.getGroup(), "添加成功");
        }
    }


    @Listen(value = MsgGetTypes.groupMsg, sort = 53)
    @Filter(at = true, code = "1731459247")
    public void jiechuzibi(GroupMsg groupMsg, MsgSender sender, CQCodeUtil cqCodeUtil) {
        sender.SETTER.setGroupBan(groupMsg.getGroup(), groupMsg.getQQ(), 0);
        /*sender.SENDER.sendGroupMsg(groupMsg.getGroup(), cqCodeUtil.getCQCode_At(groupMsg.getQQ())+" 你的禁言解除啦啦啦");*/
    }


    /* @Listen(value = MsgGetTypes.groupMsg, sort = 54)
     @ListenBreak
     @Filter(value = "^自闭.*$", keywordMatchType = KeywordMatchType.TRIM_REGEX)
     public void zibi(QQGroupMsg groupMsg, MsgSender sender) {
         if (!RobotApplication.Jurisdiction) {
             return;
         }
         PowerType powerType = groupMsg.getPowerType();
         if (powerType.isAdmin() || powerType.isOwner()) {
             sender.SENDER.sendGroupMsg(groupMsg.getGroup(), "以你的权限我给不了你想要的自闭呢");
             return;
         }
         List<String> matcher = Utils.getMatcher(groupMsg.getMsg(), "^自闭(.*)$");
         int i2 = 0;
         Random random = new Random();
         if (matcher.size() < 2 || matcher.get(1) == null || matcher.get(1).equals("")) {
             i2 = random.nextInt(1200);
             sender.SENDER.sendGroupMsg(groupMsg.getGroup(), "没有设置自闭时间吗？是要交给我吗 让我看看心情.....那就禁言" + i2 + "分钟吧(偷偷告诉你，禁言期间在群里@我可以自助解除禁言哦)");
         } else {
             String regEx = "[^0-9]";
             Pattern p = Pattern.compile(regEx);
             Matcher m = p.matcher(matcher.get(1));
             String trim = m.replaceAll("").trim();


             if (trim.length() > 0&&trim.length() <6) {
                 i2 = Integer.parseInt(trim);

                 if (i2 < 1) {
                     i2 = random.nextInt(1200);
                     sender.SENDER.sendGroupMsg(groupMsg.getGroup(), "0?不不不这怎么行呢 就给你禁言" + i2 + "分钟吧(偷偷告诉你，禁言期间在群里@我可以自助解除禁言哦)");
                 } else {
                     sender.SENDER.sendGroupMsg(groupMsg.getGroup(), "明白了，是要禁言" + i2 + "分钟吧(偷偷告诉你，禁言期间在群里@我可以自助解除禁言哦)");
                 }

             } else if (trim.length() > 6) {
                 i2 = 43200;
             } else {
                 i2 = random.nextInt(1200);
                 sender.SENDER.sendGroupMsg(groupMsg.getGroup(), "看不懂你在说什么呢 让我看看心情.....就给你禁言" + i2 + "分钟吧(偷偷告诉你，禁言期间在群里@我可以自助解除禁言哦)");
             }
         }


         int i = random.nextInt(10);
         if (i <= 2&&i2 < 43200) {
             int i3 = random.nextInt(20) + 1;
             i2 = i3 * i2;
             sender.SENDER.sendGroupMsg(groupMsg.getGroup(), "恭喜你抽中了时长超级加倍大礼包！时长加倍了" + i3 + "倍，要感谢我哦");
         }
         if (i2 >= 43200) {
             sender.SENDER.sendGroupMsg(groupMsg.getGroup(), "这....这已经是人家的极限了，请收下");
             i2 = 43199;
         }

         sender.SETTER.setGroupBan(groupMsg.getGroup(), groupMsg.getQQ(), i2 * 60);
     }
 */
    @Listen(value = MsgGetTypes.groupMsg, sort = 55)
    @ListenBreak
    @Filter(value = "^\\.文字识别.*\\..*.*\\[CQ:image,file\\=.*", keywordMatchType = KeywordMatchType.TRIM_REGEX)
    public void OCR(GroupMsg groupMsg, MsgSender sender) throws InterruptedException, IOException {


        if (!RobotApplication.Jurisdiction) {
            return;
        }

        CQCodeUtil codeUtil = CQCodeUtil.build();
        List<String> list = Utils.getMatcher(groupMsg.getMsg(), "^\\.文字识别.*\\.(.*).*\\[");
        if (list == null) {
            return;
        }

        List<CQCode> cqCodeFromMsg = codeUtil.getCQCodeFromMsg(groupMsg.getMsg());
        String url1 = cqCodeFromMsg.get(0).get("url");
        String ocr = Badiushibie.OCR(url1, OCRCheck.get(list.get(1)));
        sender.SENDER.sendGroupMsg(groupMsg.getGroup(), ocr);
    }

    @Listen(value = MsgGetTypes.groupMsg, sort = 56)
    @ListenBreak
    @Filter(value = "^\\.添加表情包.*\\[CQ:image,file\\=.*", keywordMatchType = KeywordMatchType.TRIM_REGEX)
    public void addemoji(GroupMsg groupMsg, MsgSender sender, CQCodeUtil codeUtil) throws InterruptedException, IOException {
        if (!RobotApplication.groupcode) {
            return;
        }
        if (!RobotApplication.Jurisdiction) {
            return;
        }
        List<CQCode> cqCodeFromMsg = codeUtil.getCQCodeFromMsg(groupMsg.getMsg());

        for (CQCode a : cqCodeFromMsg) {
            String url = a.get("url");
            groupService.addEmoji(url);
        }
        sender.SENDER.sendGroupMsg(groupMsg.getGroup(), "添加成功");
    }

    @Listen(value = MsgGetTypes.groupMsg, sort = 57)
    @ListenBreak
    @Filter(value = "^\\.图片搜索.*\\[CQ:image.*", keywordMatchType = KeywordMatchType.TRIM_REGEX)
    public void PixivSearch(GroupMsg groupMsg, MsgSender sender) {
        if (!RobotApplication.Jurisdiction) {
            return;
        }
        final DelayHelper delayHelper = DelayHelper.getInstance();
        Runnable task = () -> {


            CQCodeUtil codeUtil = CQCodeUtil.build();
            List<CQCode> cqCodeFromMsg = codeUtil.getCQCodeFromMsg(groupMsg.getMsg());
            if (cqCodeFromMsg == null || cqCodeFromMsg.size() < 1) {
                sender.SENDER.sendGroupMsg(groupMsg.getGroup(), "未在信息中获取到图片");
                return;
            }
            String url = cqCodeFromMsg.get(0).get("url");
            Document doc = null;
            try {
                doc = Jsoup.connect("https://saucenao.com/search.php")
                        .timeout(10000)
                        .data("url", url)
                        .data("frame", "1")
                        .data("hide", "0")
                        .data("database", "999")
                        .userAgent("Mozilla")
                        .post();
            } catch (IOException e) {
                e.printStackTrace();
            }
            Elements eles = doc.getElementsByTag("title");
            if (eles.text().equals("SauceNAO Error")) {
                sender.SENDER.sendGroupMsg(groupMsg.getGroup(), "上传图片失败");
                return;
            }
            Elements select = doc.select("div.resultsimilarityinfo");
            Element c = select.first();
            Float f = Float.parseFloat(c.html().replaceAll("%", "").trim());
            if (f < 85) {
                sender.SENDER.sendGroupMsg(groupMsg.getGroup(), "未查询到相似图片");
                return;
            }


            Element resulttitle = doc.select("div.resulttitle").first();
            Element resultcontentcolumn = doc.select("div.resultcontentcolumn").first();
            String imgName = "";
            String author = "";
            String imgurl = "";
            String zid = "";
            String newurl = null;
            resultcontentcolumn.select("strong").remove();
            resultcontentcolumn.select("br").remove();
            resultcontentcolumn.select("span").remove();
            imgName = resulttitle.select("strong").first().text();
            if (imgName.equals("Creator:")) {
                resulttitle.select("strong").remove();
                resulttitle.select("br").remove();
                author = resulttitle.text();
                imgName = "无";
            } else {
                author = resultcontentcolumn.select("a").last().text();
            }
            imgurl = resultcontentcolumn.select("a").first().attr("href");
            zid = resultcontentcolumn.select("a").first().text();
            if (zid != null) {
                String json = null;
                try {
                    json = Jsoup.connect("https://www.pixivdl.net/api/pixiv/info?zid=" + zid).ignoreContentType(true).execute().body();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                JSONObject obj = JSONObject.parseObject(json);
                newurl = obj.getJSONObject("result").getJSONObject("info").getJSONArray("urls").getJSONObject(0).getJSONObject("urls").getString("original");
                newurl = newurl.replaceAll("i.pximg", "www.pixivdl");

            }


            List<String> matcher = Utils.getMatcher(newurl, "[^\\.]\\w*$");


            String path = "C:\\酷Q Pro\\data\\image\\test." + matcher.get(0);
            int i = FileUtil.downloadPicture(newurl, path);
            if (i == 1) {
                sender.SENDER.sendGroupMsg(groupMsg.getGroup(), "[CQ:image,file=test." + matcher.get(0) + "]");
                String s = (zid == null) ? ("") : ("\n国内链接为" + newurl);
                sender.SENDER.sendGroupMsg(groupMsg.getGroup(), "作品名为：" + imgName + "\n作者为：" + author + "\nPixivId为：" + zid + "\n原图链接为" + imgurl + s);

            }

        };

        delayHelper.delayTask(task, 1000, TimeUnit.MILLISECONDS);


    }

    @Listen(value = MsgGetTypes.groupMsg, sort = 57)
    @ListenBreak
    @Filter(value = "^\\.添加装备.*", keywordMatchType = KeywordMatchType.TRIM_REGEX)
    public void addequip(GroupMsg groupMsg, MsgSender sender) {

    }

    @Listen(value = MsgGetTypes.groupMsg, sort = 110)
    @Filter(value = ".*\\[CQ:image.*", keywordMatchType = KeywordMatchType.TRIM_REGEX)
    public void jianhuang(GroupMsg groupMsg, MsgSender sender, CQCodeUtil codeUtil) {
        if (!RobotApplication.groupcode) {
            return;
        }


        List<CQCode> cqCodeFromMsg = codeUtil.getCQCodeFromMsg(groupMsg.getMsg());

        for (CQCode a : cqCodeFromMsg) {
            String url1 = a.get("url");
            // 查询是否为表情包
            if (groupService.selectEmoji(url1)) {
                continue;
            }
            List<Jianhuang> simple = Badiushibie.simple(url1);
            if (simple == null || simple.size() < 1) {
                return;
            }
            try {
                boolean p = Utils.Appraisal(simple, sender, groupMsg);
                if (p) {
                    //此图片为正常图片，添加至数据库
                    groupService.addEmoji(url1);
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }


    }

}
